package model

import (
	"encoding/json"
	"github.com/syndtr/goleveldb/leveldb"
)

var DB *leveldb.DB

func init() {
	DB, _ = leveldb.OpenFile("./db", nil)
}

type AppInfo struct {
	Name         string `json:"name"`
	AppAddr      string `json:"app_addr"`
	ServerAddr   string `json:"server_addr"`
	LogsAddr     string `json:"logs_addr"`
	RunAddr      string `json:"run_addr"`
	ShutdownAddr string `json:"shutdown_addr"`
}

type AppInfoDB int

func (AppInfoDB) Write(s AppInfo) {
	bs, _ := json.Marshal(s)
	DB.Put([]byte(s.Name), bs, nil)
}

func (AppInfoDB) Del(key string) {
	DB.Delete([]byte(key), nil)
}

func (AppInfoDB) Get(key string) AppInfo {
	bs, _ := DB.Get([]byte(key), nil)
	var s AppInfo
	json.Unmarshal(bs, &s)
	return s
}

func (AppInfoDB) ReadAll() []AppInfo {
	iter := DB.NewIterator(nil, nil)
	var datas []AppInfo
	for iter.Next() {
		bs := iter.Value()
		data := AppInfo{}
		json.Unmarshal(bs, &data)
		datas = append(datas, data)
	}
	return datas
}
